<template>
  <div class="photo-view">
    <template v-if="src">
      <div class="view-main">
        <div class="img-view">
          <img :src="src" class="img" @load="imgLoad" />
        </div>
      </div>
      <div class="tool-bar">
        <template v-if="photoLoaded">
          <el-button @click="onMenuClick('cancel')" class="btn" type="default" size="default">取消</el-button>
          <el-button @click="onMenuClick('next')" class="btn" type="danger" size="default">下一步</el-button>
        </template>
        <template v-else>
          <p>照片EXIF数据读取中...</p>
        </template>
      </div>
    </template>
  </div>
</template>


<script setup>
import {ref, onMounted, onBeforeUnmount, defineProps, defineEmits, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import ExifReader from 'exifreader'
const piexif = require('piexifjs')
const $emit = defineEmits(['menu-click'])
const photoLoaded = ref(false)
let exifData = null

const props = defineProps({
  // 文件
  file: {
    type: Object,
    required: true,
    default() {
      return null
    }
  }
})

const src = computed(() => {
  return props.file ? window.URL.createObjectURL(props.file) : ''
})


const imgLoad = () => {
  const file = props.file
  ExifReader.load(file, {includeUnknown: true}).then(tags => {
    const {
      FNumber,
      ApertureValue, // 莱卡某些镜头光圈值
      ExposureTime,
      FocalLengthIn35mmFilm,
      FocalLength,
      ISOSpeedRatings,
      DateTimeOriginal,
      LensModel,
      Lens,
      LensSpecification,
      Model,
    } = tags
    const missExif = !tags || !ExposureTime || !DateTimeOriginal
    if (missExif) {
      ElMessageBox.alert('照片EXIF数据缺失，将模拟EXIF数据！', '提示', {
        showConfirmButton: true,
        confirmButtonText: '继续',
        showClose: false,
        callback() {
          
        }
      })
    }
    // File => base64
    // 创建一个新的 FileReader 对象
    let reader = new FileReader()
    // 读取 File 对象
    reader.readAsDataURL(file)
    reader.onload = () => {
      const data = piexif.load(reader.result)
      // 获取镜头型号
      let lensModel // 镜头型号
      if (lensModel || Lens || LensSpecification) {
        lensModel = (LensModel || Lens)?.description // 镜头型号
        lensModel = lensModel || (LensSpecification?.description.replace('f/0', ''))
      }
      if (data.Exif['42036'] && !lensModel) {
        lensModel = data.Exif['42036'].replace(/[^(a-z|\d|/|\-|.)]/igm, ' ').trim()
      }
      if (data.Exif['37500'] && !data.Exif['42036'] && !lensModel) {
        const extracts = data.Exif['37500'].replace(/[^(a-z|\d| |/|\-|.)]/igm, '[]')
        let list = extracts.split('[]').filter(str => str.length > 5).map(item => item.trim())
        list = list.filter(item => /\\*[F]+\d+(\.\d)*/igm.test(item) && item.indexOf(' ') > 0)
        lensModel = list[0]
      }

      lensModel = lensModel || (missExif ? 'LEICA SUMMICRON-SL 35 f/2 ASPH.' : 'Manual lens'.toUpperCase())
      
      const model = !missExif ? Model.description.trim().toUpperCase() : 'LEICA M11' // 相机型号
      const shootTime = !missExif ? DateTimeOriginal.description.replace(/(\d{4}):(\d{2}):(\d{2})/g, '$1.$2.$3').trim() : '2023.05.20 13:14:20' // 拍摄日期
      // 拍摄参数 '300mm f/8 1/320 ISO640'
      let shootParameters = ''
      if (FocalLengthIn35mmFilm || FocalLength) {
        shootParameters += (String((FocalLengthIn35mmFilm || FocalLength).description).replace(/(\d+)[ ]*[mm]*/g, '$1')) + 'mm'
      }
      if (FNumber || ApertureValue) {
        shootParameters += ' ' + (FNumber ? FNumber.description : ('f/' + (Number((ApertureValue.description * 1).toFixed(2)))))
        shootParameters += ' '
      }
      shootParameters += ExposureTime ? ExposureTime.description : ''
      shootParameters += ISOSpeedRatings ? ' ISO' + ISOSpeedRatings.description : ''
      if (missExif) {
        shootParameters = '35mm f/5.6 1/320 ISO400'
      }
      exifData = {
        model,
        lensModel,
        shootTime,
        shootParameters
      }
      window.localStorage.setItem('originalExif', JSON.stringify(exifData)) // 重置相框编辑内容的exif数据缓存
      reader.onload = null
      reader = null
      photoLoaded.value = true
    }
  })
}

onMounted(() => {

})

onBeforeUnmount(() => {
  window.URL.revokeObjectURL(src.value)
})

const onMenuClick = name => {
  $emit('menu-click', {
    name,
    exifData,
  })
  exifData = null
}




</script>



<style lang="less" scoped>
.photo-view {
  width: 100%;
  flex: 1;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  .view-main {
    width: 100%;
    flex: 1;
    padding: 30px;
    position: relative;
  }
  .img-view {
    position: absolute;
    left: 30px;
    top: 30px;
    right: 30px;
    bottom: 30px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // 遮盖图片: 禁止拖拽图片到电脑桌面
    &:after {
      content: "";
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0,0,0,0);
    }
  }

  img {
    width: auto;
    height: 100%;
  }

  .tool-bar {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 30px;
  }
}
</style>
